package com.bzsg.simpleMediaPlayer.viewModel

import android.content.ContentUris
import android.content.Context
import android.content.res.AssetManager
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.Surface
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import com.bzsg.simpleMediaPlayer.data.PlayerState
import com.bzsg.simpleMediaPlayer.data.PlayerStateCode
import com.bzsg.simpleMediaPlayer.extend.requestIO
import com.bzsg.simpleMediaPlayer.extend.requestMain
import com.bzsg.simpleMediaPlayer.jni.NativeCodecCallback
import com.bzsg.simpleMediaPlayer.jni.NativeCodecHandler
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject


@HiltViewModel
class PlayerViewModel
@Inject
constructor(
    @ApplicationContext private val aContext: Context, savedStateHandle: SavedStateHandle,
) : ViewModel(), NativeCodecCallback {
    companion object {
        init {
            System.loadLibrary("codec")
        }
    }
    private var _totalDuration by mutableStateOf(0.0)
    val totalDuration: Double get() = _totalDuration

    private var _currentPosition by mutableStateOf(0.0)
    val currentPosition: Double get() = _currentPosition

    private var surface: Surface? = null
    private var assetManager: AssetManager? = null

    private val mediaId: Long = (savedStateHandle["MEDIA_ID_EXTRA"]) ?: 0
    private val nativeHandler: NativeCodecHandler =
        NativeCodecHandler.NativeImpl().apply {
            setCallback(this@PlayerViewModel) // 设置回调到当前 ViewModel
        }

    // 使用lazy避免过早初始化
    private val _playerState by lazy {
        MutableStateFlow<PlayerState>(PlayerState.Idle).also {
            triggerInitialIdle() // 安全触发初始IDLE
        }
    }

    // 新增：安全触发初始IDLE
    private fun triggerInitialIdle() {
        requestIO {
            // 确保所有依赖已就绪
            onStateChanged(PlayerStateCode.IDLE, null)
        }
    }

    val playerState: StateFlow<PlayerState> = _playerState.asStateFlow()

    // 设置播放资源
    fun setSurface(
        surface: Surface,
        assetManager: AssetManager,
    ) {
        this.surface = surface
        this.assetManager = assetManager
        if (_playerState.value is PlayerState.Initialized) {
            preparePlayer()
        }

    }

    // 准备播放器
    fun preparePlayer() {
        requestIO {
            surface?.let { s ->
                assetManager?.let { am ->
                    nativeHandler.prepare(s, am)
                }
            } ?: run {
                _playerState.value = PlayerState.Error(-1, "Surface 或 AssetManager 未初始化")
            }
        }
    }

    fun changeSurface(
        width: Int,
        height: Int,
        isFullScreen: Boolean,
    ) {
        nativeHandler.changeSurface(width, height, isFullScreen)
    }

    // 开始播放
    fun startPlayback() {
        requestMain {
            if (playerState.value is PlayerState.Prepared) {
                nativeHandler.start()
            }
        }
    }

    // 控制方法
    fun pause() =
        nativeHandler.pause().also {
            _playerState.value = PlayerState.Paused(0)
        }

    fun resume() =
        nativeHandler.resume().also {
            _playerState.value = PlayerState.Playing(0.00)
        }

    fun stop() =
        nativeHandler.stop().also {
            _playerState.value = PlayerState.Stopped
        }

    fun seekTo(position: Float) = nativeHandler.seekTo(position)

    override fun onStateChanged(
        state: PlayerStateCode,
        extras: Bundle?
    ) {
        Log.i("fhq", "onStateChanged: $state $extras ")
        when (state) {
            PlayerStateCode.IDLE -> {
                _playerState.value = PlayerState.Idle
                val collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)
                val videoUri = ContentUris.withAppendedId(collection, mediaId)
                val pfd = aContext.contentResolver.openFileDescriptor(videoUri, "r")
                nativeHandler.setDataSource(pfd?.fd ?: 0)
            }

            PlayerStateCode.INITIALIZED -> {
                _playerState.value = PlayerState.Initialized
            }

            PlayerStateCode.PREPARED -> {
                val height = (extras?.getString("height") ?: "0").toInt()
                val width = (extras?.getString("width") ?: "0").toInt()
                val totalDuration = (extras?.getString("duration")  ?: "0").toDouble()
                Log.i("fhq", "onStateChanged: $height$width")
                _playerState.value = PlayerState.Prepared(Pair(height, width),totalDuration)
                _totalDuration = totalDuration // 保存总时长
                startPlayback()
            }

            PlayerStateCode.PLAYING -> {
                val currentPosition = (extras?.getString("duration")  ?: "0").toDouble()
                _playerState.value = PlayerState.Playing(currentPosition)
                _currentPosition = currentPosition
            }

            PlayerStateCode.PAUSED ->  {
                _playerState.value = PlayerState.Paused(0)

            }
            PlayerStateCode.SEEKING -> {

            }
            PlayerStateCode.COMPLETED -> {

            }
            PlayerStateCode.STOPPED -> {
            }
            PlayerStateCode.ERROR ->{}
        }
    }

    fun release() {
        nativeHandler.release()
    }

    override fun onCleared() {
        release()
        super.onCleared()
    }
}
